

#include "mekr.h"
#include <iostream>
#include "../hedmodel.h"
#include "../entity/face.h"
#include "../entity/loop.h"
#include "../entity/halfedge.h"
#include "../entity/edge.h"
#include "../entity/vertex.h"
#include "kemr.h"


MEKR::MEKR( HEDModel& _model, HalfEdge* _h1, HalfEdge* _h2 )
: m_he1( _h1 )
, m_he2( _h2 )
, m_edge( NULL )
, m_v1( _h1->getVtx()->getVertexno() )
, m_v2( _h2->getVtx()->getVertexno() )
, m_model( &_model )
{

}


void
MEKR::execute()
{
  std::cout << "\nMEKR::execute() \n";

  if( (m_he1 == NULL) && (m_he2 == NULL) )
  {
    Vertex* vtx1 = m_model->getVertex(m_v1);
    Vertex* vtx2 = m_model->getVertex(m_v2);
    m_he1 = m_model->getHalfEdge(vtx1,vtx2->getPoint()->getX(),vtx2->getPoint()->getY(),vtx2->getPoint()->getZ());
    m_he2 = m_model->getHalfEdge(vtx2,vtx1->getPoint()->getX(),vtx1->getPoint()->getY(),vtx1->getPoint()->getZ());
  }

  register HalfEdge *n_he1, *n_he2;
  Loop* l1 = m_he1->getLoop();
  Loop* l2 = m_he2->getLoop();
  Face* f = l1->getFace();

  n_he1 = l2->getLedg();
  do
  {
      n_he1->setWloop( l1 );
  }
  while((n_he1 = n_he1->getNxt()) != l2->getLedg());

  Edge* n_ed = new Edge( f->getSolid() );

  n_he1 = n_ed->addhe( m_he1->getVtx(), m_he1, PLUS);
  n_he2 = n_ed->addhe( m_he2->getVtx(), m_he2, MINUS);

  n_he1->setNxt( m_he2 );
  n_he2->setNxt( m_he1 );
  m_he2->setPrv( n_he1 );
  m_he1->setPrv( n_he2 );

  if(f->getLoopOut() == l2)
    f->setFlout( l1 );

  delete l2;

  m_edge = n_ed;
}


void
MEKR::unExecute()
{
  std::cout << "\nMEKR::unExecute() TESTING!\n";

  // checks the correct order of the half-edges that should be sent to KEV
  HalfEdge* h1 = NULL;
  HalfEdge* h2 = NULL;
  if( m_edge->getHe1()->getVtx()->getVertexno() == m_v1 )
  {
    h1 = m_edge->getHe1();  h2 = m_edge->getHe2();
  }
  else
  {
    h1 = m_edge->getHe2();  h2 = m_edge->getHe1();
  }

  KEMR kemr( h1, h2 );
  kemr.execute();

  // cleaning
  m_he1 = NULL;
  m_he2 = NULL;
  m_edge = NULL;
}







